<template>
    <div class="watchCourse common-layout">
        <el-container class="container-box">
            <el-container>
                <!-- 课程列表 -->
                <el-aside class="container-aside">
                    <VideoMenu :myCourseIDs="catebagCourseIDs" :courseGroup="courseGroup" :courseList="courseList"
                        :course="course" :files="files" :teacher-files="teacherFiles">
                    </VideoMenu>
                </el-aside>
                <el-main class="container-content">
                    <el-scrollbar class="padding20">
                        <!-- 视频 -->
                        <div v-if="showType === 'video'">
                            <Aliplayer :lessionId="currLession.ID" :question="question" :course="course" />
                        </div>
                        <div v-if="showType === 'vector'">
                            <ViewFile :num="1" :question="question" :course="course" />
                        </div>
                        <div v-if="!showType">
                            <!-- !showType -->
                        </div>
                        <!-- 跳转资料、练习 -->
                        <div class="practise-container">
                            <div v-for="(v, k) in files" :key="k">
                                <el-button class="margin-left20" size="default" type="primary" plain
                                    @click="goToPractise(v.file_URL!)">
                                    {{ v.name || `资料-${k + 1}` }}
                                </el-button>
                            </div>
                            <div v-for="(v, k) in teacherFiles" :key="k">
                                <el-button class="margin-left20" size="default" type="primary" plain
                                    @click="previewMateria(v.fileurl!)">
                                    教师资料
                                </el-button>
                            </div>
                        </div>
                        <!-- 评论区 -->
                        <CourseForum :courseGroup="courseGroup" :course="course">
                        </CourseForum>
                    </el-scrollbar>
                </el-main>
            </el-container>
        </el-container>
    </div>
</template>

<script setup lang='ts'>
import { ElMessage } from 'element-plus';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncGetAllCourseGroup, asyncGetCourseFile, asyncGetLessionByCourseid, asyncSelectCourseLession, asyncSelectCoursefile, asyncSelectPackageCatebagRelation, asyncVideoQuestion, asyncselectUsercourse } from '../../../api';
import { Storekey } from "../../../interface";
import Alymodel from '../../../mysql_interface/model';
import { getGroupedByCatebagArr } from '../../../util/cloudClass';
import Aliplayer from "./aliplayer.vue";
import CourseForum from "./courseForum.vue";
import VideoMenu from "./videoMenu.vue";
import ViewFile from "./viewFile.vue";

const p = defineProps<{
    ID: string,
    catebag?: string, // 任务跳转的可能没有该参数
    lession: string,
    pID?: string // 视频任务-预览
    taskCourseIDs?: string // 视频任务-跳转
    taskName?: string // 视频任务-跳转
}>()
const taskCourseIDs = computed(() => {
    return p.taskCourseIDs ? JSON.parse(p.taskCourseIDs) : ''
})
const pID = computed(() => {
    return p.pID ? JSON.parse(p.pID) : ''
})

const store = useStore(Storekey)
const route = useRoute()
const router = useRouter()
// 当前登录用户
const user = computed(() => {
    return store.state.user;
});
const teamId = computed(() => {
    return Number(user.value?.teamid);
});

// 获取我的课程配置 user_ID - course_ID
const myCourseMap = ref<{ [uid: number]: Alymodel.IMusercourse[] }>({})
async function getMyCourse() {
    myCourseMap.value = await asyncselectUsercourse({
        teamid: teamId.value,
        user_ID: user.value?.ID,
        _order: 'createtime'
    })
}
const catebagCourseIDs = ref<number[]>([])
// 初始化我的课程列表-用于左侧菜单栏
const initMyCourseIds = async () => {
    catebagCourseIDs.value = courseGroup.value.coursecatebag.map(e => e.cid)

    const savedCourseIDs = sessionStorage.getItem('myCourseIDs');
    if (savedCourseIDs) {
        catebagCourseIDs.value = JSON.parse(savedCourseIDs);
    }
    // 视频任务-跳转
    if (taskCourseIDs.value) {
        catebagCourseIDs.value = taskCourseIDs.value
    }
    await getMyCourse()
    // 和我的课程集合 求交集
    let myDbCourse = myCourseMap.value[Number(user.value?.ID)] || []
    catebagCourseIDs.value = catebagCourseIDs.value.filter(id => myDbCourse.find(userCID => userCID.course_ID === id))
    // 视频任务-预览
    if (p.pID) {
        // 根据代理商课包ID获取指定代理商课包 =》 课程 =》 课程组 关系 
        const { rows: data, count } = await asyncSelectPackageCatebagRelation({ ID: pID.value })
        // 按课程包分组
        const groupedByCatebagArr = getGroupedByCatebagArr(data)
        //  
        const catebag = groupedByCatebagArr.filter(catebagItem => catebagItem.cID === Number(p.catebag))
        catebagCourseIDs.value = catebag[0].packages.map(e => Number(e.course_ID))
        sessionStorage.setItem('myCourseIDs', JSON.stringify(catebagCourseIDs.value)); // 将新值保存到 sessionStorage
    }
    // 视频任务-跳转
    if (p.taskName) {
        courseGroup.value = { name: p.taskName, ID: Number(p.catebag), coursecatebag: [] }
    }
    // 课程列表
    await getCourseDetail(catebagCourseIDs.value)
    if (taskCourseIDs.value) {
        // 视频任务的课程需要按照规定顺序展示
        courseList.value = courseList.value.sort((a, b) => {
            return taskCourseIDs.value.indexOf(a.ID) - taskCourseIDs.value.indexOf(b.ID);
        });
    }
}
onMounted(async () => {
    loading.value = true;
    // 课程组-课程
    await getCourseAndCatebag()
    // 筛选课程组-课程得到我的课程
    // await initMyCourseIds()
    // 资料
    await initMaterial()
    loading.value = false;
})
const loading = ref(true)
async function getCourseAndCatebag() {
    if (p.catebag) {
        // 课包-课程
        await getCourseCatebag(p.catebag)
    }
    // 课程列表-暂时不做uid归属判断
    catebagCourseIDs.value = courseGroup.value.coursecatebag.map(e => e.cid)
    await getCourseDetail(catebagCourseIDs.value)
}
// 课程包-课程
const courseGroup = ref<Alymodel.CourseGroup>({ coursecatebag: [] })
async function getCourseCatebag(id: number | string) {
    const { rows, count } = await asyncGetAllCourseGroup({
        teamid: teamId.value, ID: id,
        _order: "paixu", _sortable: "ASC"
    })
    courseGroup.value = rows[0] || { coursecatebag: [] }
}

// 课程列表
const courseList = ref<Alymodel.IMcourse[]>([])
async function getCourseDetail(cids: number[]) {
    const { rows, count } = await asyncSelectCourseLession({
        teamid: teamId.value, ID: cids,
        _limit: 1000, _order: ["paixu", "ID"], _sortable: "ASC"
    })
    courseList.value = rows
}
// 当前查看课程 包含 lession
const course = computed(() => {
    // 默认取第一条，因为任务跳转过来的p.ID成员可能没权限查看(courseList没有此ID)
    let defaultCourse = courseList.value[0] || {} as Alymodel.IMcourse
    let curr = courseList.value.find(v => v.ID === Number(p.ID))
    return curr || defaultCourse
})
watch(course, e => {
    if (e.ID !== Number(p.ID)) {
        ElMessage({
            message: `课程组:${p.catebag}-课程:${p.ID}，马上开放请先观看其他课程!`,
            type: 'warning',
        });
    }
});
const iswatch = computed(() => {
    return true
    // return p.getuserUserCourse.some((v) => v.course_ID == Number(p.ID));
})
// 区分展示视频播放器、PDF等
const showType = ref<false | 'vector' | 'video' | 'question' | undefined>(false)
const files = ref<Alymodel.Ifileurl[]>([])
const teacherFiles = ref<Alymodel.Iteachercoursefile[]>([])
const question = ref<Alymodel.Ivideoquestion[]>([])
const currLession = ref<Alymodel.IMlession>({})
async function initMaterial() {
    try {
        if (iswatch.value) {
            const lessions = await asyncGetLessionByCourseid({ cid: course.value.ID });
            if (!lessions) {
                showType.value = false
            }
            const lessionIdx = Number(p.lession) || 0
            const lession = lessions[lessionIdx]
            if (!lession) {
                ElMessage.warning("课程马上开放请先观看其他课程!");
                showType.value = false
                return
            }
            currLession.value = (course.value?.lession || [])[lessionIdx] || {}
            const filesRet = await asyncGetCourseFile({ cid: course.value.ID });
            files.value = filesRet
            const teacherfileRet = await asyncSelectCoursefile({ cid: course.value.ID });
            teacherFiles.value = teacherfileRet
            const { type } = currLession.value;
            if (type === "video") {
                const questionRet = await asyncVideoQuestion({ lid: lession.ID });
                question.value = questionRet
            }
            showType.value = type
        }
    } catch (err) {
        console.error(err)
        ElMessage.warning("课程马上开放请先观看其他课程!!");
    }
    // showType.value = false
}
// 
watch(() => route.params, async (e) => {
    await initMaterial()
})

// 跳转练习
function goToPractise(url: string) {
    if (!url) return
    // 是否判断当前是否是saas 原Oj oj.hterobot.com
    if (url.includes("oj.hterobot.com")) {
        const { hostname, host } = window.location
        const { hash, hostname: orgHostname, host: orgHost } = new URL(url)
        url = url?.replace(orgHost, host)
    }
    window.open(url);
}
// 外部资料
function previewMateria(url: string) {
    if (!url) return
    // 是否判断当前是否是saas 原Oj oj.hterobot.com
    if (url.includes("oj.hterobot.com")) {
        const { hostname, host } = window.location
        const { hash, hostname: orgHostname, host: orgHost } = new URL(url)
        url = url?.replace(orgHost, host)
    }
    // 
    // 检查是否是可以预览的文件类型
    const previewableTypes = ['.pdf', '.jpg', '.jpeg', '.png', '.gif', '.html', '.htm'];
    const isPreviewable = previewableTypes.some(type => url.includes(type));
    if (isPreviewable) {
        window.open(url);
    } else {
        downloadFile(url)
    }
}
function downloadFile(orgUrl: string) {
    fetch(orgUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.blob();
        })
        .then(blob => {
            const decodedUrl = decodeURIComponent(orgUrl);
            // 获取文件名
            const filename = decodedUrl.split('/').pop();
            // 创建一个URL，指向blob数据
            const url = window.URL.createObjectURL(blob);
            // 创建一个<a>标签
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = filename || "教师资料";
            document.body.appendChild(a);
            a.click();
            // 下载完成后移除<a>标签和URL对象
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        })
        .catch(error => console.error('下载失败：', error));
}

</script>

<style scoped>
.container-box {
    padding: var(--container-margin) 5% 0;
    margin: var(--container-margin) 0rem 0 0rem;
    /* 外边距 */
    --container-margin: 20px;
    --container-padding: 15px;
    --container-header-height: 24vh;
    --container-bg-color: #fff
}

.container-aside {
    min-width: 20%;
    background: var(--container-bg-color);
}

.container-content {
    height: calc(100vh - 64px - 2 * var(--container-margin));
    margin-left: var(--container-margin);
    background: var(--container-bg-color);
    padding: 0;
    /* padding: var(--container-margin); */
    /* min-width: 70%; */
}

.practise-container {
    padding: var(--container-margin);
    display: flex;
    align-items: center;
    justify-content: flex-end;
}
</style>

<style>
/* 设置纵向向滚动条宽高为0 */
#app.ojSass .watchCourse .container-aside .el-scrollbar__bar.is-vertical {
    width: 0;
    height: 0;
}
</style>